<template>
  <div class="form-con">
    <el-form :model="Spu">
      <el-row type="flex" justify="space-around">
        <!-- 左侧 -->
        <el-col :span="12">
          <el-form-item label="商品图片" :label-width="formlabelwidth">
            <spu-images
              ref="unload"
              :successEvent="createSpu"
              :selectImages="selectImages"
            ></spu-images>
          </el-form-item>
          <el-form-item label="类名称" :label-width="formlabelwidth">
            <el-input v-model="Spu.SpuName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="标题语" :label-width="formlabelwidth">
            <el-input v-model="Spu.Caption" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" :label-width="formlabelwidth">
            <el-select v-model="Spu.CategoryId" placeholder="请选择模板">
              <el-option
                v-for="cate in categorys"
                :key="cate.Id"
                :label="cate.CatName"
                :value="cate.Id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="价格" :label-width="formlabelwidth">
            <el-input v-model="Spu.Price" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品简介" :label-width="formlabelwidth">
            <el-input type="textarea" v-model="Spu.Introduction"></el-input>
          </el-form-item>
          <el-form-item :label-width="formlabelwidth">
            <el-button type="primary" @click="submit">确认</el-button>
            <el-button @click="$router.replace('/shop')">取消</el-button>
          </el-form-item>
        </el-col>
        <!-- 右侧 -->
        <el-col :span="11">
          <div class="switch-con" style="display: flex">
            <el-form-item label="启用规格" :label-width="formlabelwidth">
              <el-switch
                v-model="Spu.IsEnableSpec"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="1"
                inactive-value="0"
              ></el-switch>
            </el-form-item>
            <el-form-item label="启用小料" :label-width="formlabelwidth">
              <el-switch
                v-model="Spu.IsEnableMaterial"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="1"
                inactive-value="0"
                @change.once="getMaterial"
              ></el-switch>
            </el-form-item>
            <el-form-item label="是否新品" :label-width="formlabelwidth">
              <el-switch
                v-model="Spu.IsNew"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="1"
                inactive-value="0"
              ></el-switch>
            </el-form-item>
            <el-form-item label="是否热销" :label-width="formlabelwidth">
              <el-switch
                v-model="Spu.IsHotSale"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="1"
                inactive-value="0"
              ></el-switch>
            </el-form-item>
          </div>

          <!-- 规格选择 -->
          <el-card v-if="Spu.IsEnableSpec == 1" shadow="hover">
            <div class="flex-col">
              <div class="flex-row justify-between align-center">
                <span>规格选择</span>
                <el-select v-model="Spu.TPLId" placeholder="请选择模板">
                  <el-option
                    v-for="tpl in templates"
                    :key="tpl.Id"
                    :label="tpl.TplName"
                    :value="tpl.Id"
                  ></el-option>
                </el-select>
              </div>

              <template v-if="Spu.TPLId">
                <el-form-item
                  v-for="item in specs"
                  :key="item.Id"
                  :label="item.SpecName"
                  :label-width="formlabelwidth"
                >
                  <el-checkbox-group v-model="selectSpecs">
                    <el-checkbox
                      v-for="value in item.Options.split(',')"
                      :key="value.Id"
                      :label="item.SpecName + '-' + value"
                      >{{ value }}</el-checkbox
                    >
                  </el-checkbox-group>
                </el-form-item>
              </template>
            </div>
          </el-card>

          <!-- 小料选择 -->
          <el-card v-if="Spu.IsEnableMaterial == 1" shadow="hover">
            <div class="flex-col">
              <div class="flex-row justify-between align-center">
                <span>小料选择</span>
              </div>

              <template>
                <el-form-item>
                  <el-checkbox-group v-model="selectMate">
                    <el-checkbox
                      v-for="mate in materials"
                      :key="mate.Id"
                      :label="'小料' + '-' + mate.MatName + '-' + mate.Price"
                      >{{ mate.MatName }}</el-checkbox
                    >
                  </el-checkbox-group>
                </el-form-item>
              </template>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-form>

    <el-dialog :visible.sync="SkuListVisible"> </el-dialog>
  </div>
</template>

<script>
import SpuImages from "./components/SpuImages.vue";
import SkuList from "./components/Sku/SkuList.vue";
import TemplateApi from "@/api/TemplateApi.js";
import MaterialApi from "@/api/MaterialApi.js";
import SpecApi from "@/api/SpecApi.js";
import CategoryApi from "@/api/CategoryApi.js";
import SpuApi from "@/api/SpuApi.js";

export default {
  data() {
    return {
      formlabelwidth: "80px",
      SkuListVisible: false,
      categorys: [],
      templates: [],
      specs: [],
      selectSpecs: [],
      materials: [],
      selectMate: [],
      Spu: {
        SpuName: "",
        Caption: "",
        Price: 0,
        CategoryId: _,
        TPLId: null,
        ImageUrl: "",
        ImageUrls: [],
        Introduction: "",
        SpecItems: [],
        ParaItems: "",
        MaterialItems: [],
        IsEnableSpec: 0,
        IsEnableMaterial: 0,
        IsNew: 0,
        IsHotSale: 0,
      },
    };
  },
  components: {
    SpuImages,
    SkuList,
  },
  methods: {
    // 确认事件
    submit() {
      // 上传图片
      this.$refs.unload.submitUpload();
    },

    // 创建spu并上传
    createSpu() {
      let spu = { ...this.Spu };

      spu.SpecItems = JSON.stringify(this.trimSpecs(this.selectSpecs));
      spu.MaterialItems = JSON.stringify(this.trimMaterials(this.selectMate));
      spu.ImageUrls = spu.ImageUrls.join(",");
      console.log("SPu", spu);

      // 判断是否开启小料
      if (spu.IsEnableSpec == 1) {
        let skus = this.createSkus(spu);

        console.log("skus", skus);
        SpuApi.add(spu, skus).then((res) => {
          if (res.code == 1) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.$router.replace("/shop");
          }
        });
      } else {
        SpuApi.add(spu).then((res) => {
          if (res.code == 1) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.$router.replace("/shop");
          }
        });
      }
    },

    // 选中图片
    selectImages(imgUrl) {
      if (this.Spu.ImageUrl == ""){
        this.Spu.ImageUrl = imgUrl;
      } 
        this.Spu.ImageUrls.push(imgUrl);
    },

    // 创建sku规格
    createSkuSpecs(specArr) {
      if (specArr.length === 0) {
        return [[]];
      } else {
        const [head, ...tail] = specArr;
        const rest = this.createSkuSpecs(tail);
        const pairs = head.values.map((value) => {
          return rest.map((r) => {
            return [value, ...r];
          });
        });
        return [].concat(...pairs);
      }
    },

    // 整理规格
    trimSpecs() {
      let specs = [];
      this.selectSpecs.reduce((arr, text) => {
        let param = text.split("-");
        let name = param[0];
        let valText = param[1];
        let value = { value: valText, is_selected: false };

        let exist = false;
        specs.forEach((item) => {
          if (item.name === name) {
            exist = true;
            item.values.push(value);
          }
        });

        if (!exist) {
          specs.push({
            name,
            values: new Array(value),
          });
        }
      }, 0);
      return specs;
    },

    // 整理小料
    trimMaterials() {
      let specs = [];
      this.selectMate.reduce((arr, text) => {
        let param = text.split("-");
        let name = param[0];
        let valText = param[1];
        let price = param[2];
        let value = { value: valText, price, is_selected: false };

        let exist = false;
        specs.forEach((item) => {
          if (item.name === name) {
            exist = true;
            item.values.push(value);
          }
        });

        if (!exist) {
          specs.push({
            name,
            values: new Array(value),
          });
        }
      }, 0);
      return specs;
    },

    // 创建sku数组
    createSkus(spu) {
      let specs = this.trimSpecs();
      // 生成sku规格数据
      let skuSpecs = this.createSkuSpecs(specs);
      // 获取分类名称
      let categoryName;
      console.log(spu);
      this.categorys.forEach((item) => {
        if (item.Id == spu.CategoryId) return (categoryName = item.CatName);
      });
      // 生成sku数据
      return skuSpecs.map((item) => {
        let specText = item.map((spec) => spec.value).join(",");

        let sku = {
          SN: "",
          SkuName: spu.SpuName,
          Price: spu.Price,
          Num: 100,
          AlertNum: 10,
          ImageUrl: spu.ImageUrl,
          ImageUrls: spu.ImageUrls,
          CategoryId: spu.CategoryId,
          CategoryName: categoryName,
          SaleNum: 0,
          CommentNum: 0,
          Spec: specText,
          Status: 2,
        };
        return sku;
      });
    },

    getMaterial() {
      MaterialApi.getAll().then((res) => {
        this.materials = res.data;
      });
    },
  },
  watch: {
    "Spu.TPLId": {
      handler(newVal) {
        // 获取模板下的规格
        SpecApi.getByTplId(newVal).then((res) => {
          this.specs = res.data;
        });

        // 重置选中的规格
        this.selectSpecs = [];
      },
    },
  },
  created() {
    TemplateApi.getAll().then((res) => {
      this.templates = res.data;
    });
    CategoryApi.getAll().then((res) => {
      this.categorys = res.data;
    });
  },
};
</script>

<style scoped>
.el-col {
}
.el-card {
  margin: 10px 0;
}
</style>